package pers.li.dao;

import pers.li.model.Address;
import pers.li.utils.DataProcess;

import java.util.List;

public class AddressDao {
    private final DataProcess dp = new DataProcess(true);

    public List<Address> getAddressListByUserId(Integer userId) {
        String sql = "SELECT *FROM t_address WHERE user_id = ?";
        return dp.getObjectList(sql, Address.class, userId);
    }

    public Address getAddress(Integer addressId) {
        String sql = "select *from t_address where addr_id = ?";
        return dp.getObject(sql, Address.class, addressId);
    }

    public Boolean addAddress(Address address) {
        String sql = "insert into t_address\n" +
                "(user_id, addr_province, addr_city, addr_area, addr_content, addr_receiver, addr_tel)\n" +
                "values (?, ?, ?, ?, ?, ?, ?);";
        return dp.insertRow(sql, address.getUserId()
                , address.getAddrProvince(), address.getAddrCity(), address.getAddrArea()
                , address.getAddrContent(), address.getAddrReceiver(), address.getAddrTel()) != 0;
    }

    public Boolean updateAddress(Address address) {
        String sql = "update t_address\n" +
                "set addr_province = ?,\n" +
                "    addr_city     = ?,\n" +
                "    addr_area     = ?,\n" +
                "    addr_content  = ?,\n" +
                "    addr_receiver = ?,\n" +
                "    addr_tel      = ?\n" +
                "where addr_id = ?";
        return dp.updateRow(sql, address.getAddrProvince(), address.getAddrCity(), address.getAddrArea()
                , address.getAddrContent(), address.getAddrReceiver(), address.getAddrTel(), address.getAddrId()) != 0;
    }

    public Boolean delAddress(Integer addressId) {
        String sql = "delete from t_address where addr_id = ?";
        return dp.deleteRow(sql, addressId) != 0;
    }

    public Boolean cancelDefault(Integer userId) {
        String sql = "update t_address\n" +
                "set addr_isdefault = 0\n" +
                "where user_id = ? AND addr_isdefault = 1";
        dp.updateRow(sql, userId);
        return true;
    }

    public Boolean setDefault(Integer addressId) {
        String sql = "update t_address\n" +
                "set addr_isdefault = 1\n" +
                "where addr_id = ?";
        return dp.updateRow(sql, addressId) != 0;

    }

}
